﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition.Hosting;
using System.Linq;
using System.Reflection;
using System.Text;

namespace StoryMaker.Plugins
{
    public class Startup
    {
        #region Singleton
        private Startup()
        {
            catalog.Catalogs.Add(new DirectoryCatalog((@"\.")));
            Container = new CompositionContainer(catalog);
        }
        private static Startup _instance;
        public static Startup Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new Startup();
                }
                return _instance;
            }
        }
        #endregion

        public void LoadAssemblies()
        {
            var compositionBatch = new CompositionBatch();
            Container.Compose(compositionBatch);
            this.DownloadAssemblies(catalog);
            //System.ComponentModel.Composition.AttributedModelServices.SatisfyImportsOnce(
        }

        private AggregateCatalog catalog = new AggregateCatalog();
        public readonly CompositionContainer Container;

        private void DownloadAssemblies(AggregateCatalog catalog)
        {
            AddAssemblies(System.IO.Directory.GetFiles(".", "*.dll").Union(System.IO.Directory.GetFiles(".", "*.exe")).Select(x => Assembly.LoadFrom(x)), catalog);
        }

        private void AddAssemblies(IEnumerable<Assembly> assemblies, AggregateCatalog catalog)
        {
            var assemblyCatalogs = new AggregateCatalog();
            foreach (Assembly assembly in assemblies)
            {
                assemblyCatalogs.Catalogs.Add(new AssemblyCatalog(assembly));
            }
            catalog.Catalogs.Add(assemblyCatalogs);
        }
    }
}
